package com.mars.module.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.mars.common.request.sys.SysPostRequest;
import com.mars.common.response.PageInfo;
import com.mars.framework.exception.ServiceException;
import com.mars.module.system.entity.BaseEntity;
import com.mars.module.system.entity.SysPost;
import com.mars.module.system.entity.SysUserPost;
import com.mars.module.system.mapper.SysPostMapper;
import com.mars.module.system.mapper.SysUserPostMapper;
import com.mars.module.system.service.ISysPostService;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 功能描述
 *
 * @author Mars.wq [wqexpore@163.com]
 * @version 1.0
 * @date 2023-11-03 22:43:10
 */
@Service
@AllArgsConstructor
public class SysPostServiceImpl implements ISysPostService {

    private final SysPostMapper sysPostMapper;

    private final SysUserPostMapper sysUserPostMapper;


    @Override
    public void add(SysPostRequest request) {
        SysPost sysPost = new SysPost();
        BeanUtils.copyProperties(request, sysPost);
        sysPostMapper.insert(sysPost);
    }

    @Override
    public void update(SysPostRequest request) {
        SysPost sysPost = new SysPost();
        BeanUtils.copyProperties(request, sysPost);
        sysPostMapper.updateById(sysPost);
    }

    @Override
    public void delete(Long id) {
        // 岗位和用户的关联关系
        Long count = sysUserPostMapper.selectCount(Wrappers.lambdaQuery(SysUserPost.class).eq(SysUserPost::getPostId, id));
        if (count > 0) {
            throw new ServiceException("当前岗位已绑定用户,无法删除");
        }
        sysPostMapper.deleteById(id);
    }

    @Override
    public PageInfo<SysPost> pageList(SysPostRequest request) {
        LambdaQueryWrapper<SysPost> wrapper = Wrappers.lambdaQuery(SysPost.class)
                .like(StringUtils.isNotEmpty(request.getPostName()), SysPost::getPostName, request.getPostName())
                .like(StringUtils.isNotEmpty(request.getPostCode()), SysPost::getPostCode, request.getPostCode())
                .orderByDesc(BaseEntity::getCreateTime);
        IPage<SysPost> page = sysPostMapper.selectPage(request.page(), wrapper);
        return PageInfo.build(page);
    }

    @Override
    public List<SysPost> getList() {
        return sysPostMapper.selectList(null);
    }

    @Override
    public SysPost detail(Long id) {
        return sysPostMapper.selectById(id);
    }
}
